class MyWebSocket {
  constructor(options) {
    const { url, isHeart, isRetry, callback } = options
    this.ws = null
    this.url = url
    this.isHeart = isHeart
    this.isRetry = isRetry
    this.time = null // 计时器引用
    this.timeout = 3000 // 重试频率
    this.status = null
  }
  connect() {
    this.ws = new WebSocket(this.url)
    this.ws.onopen = (e) => {
      this.status = 'open' // 防止status一直是close
      console.log('ws连接成功 ', e)
      if (this.isHeart) {
        this.heartCheck()
      }
    }
    this.ws.onmessage = (e) => {
      console.log('客户端收到响应', e)
    }
    this.ws.onerror = (e) => {
      if (this.isRetry) {
        this.retry()
      }
    }
    this.ws.onclose = (e) => {
      if (this.isRetry) {
        this.retry()
      }
    }
  }
  // 心跳机制
  heartCheck() {
    this.time = setInterval(() => {
      /**
       * readyState
       * 0 连接尚未建立
       * 1 WebSocket的链接已经建立
       * 2 连接正在关闭
       * 3 连接正在关闭
       */
      if (this.ws.readyState === 1) {
        this.ws.send(JSON.stringify({ type: 'ping' }))
      }
    }, this.timeout)
  }
  // 重连
  retry() {
    console.log('ws重连')
    clearInterval(this.time)
    // 主动关闭不会触发重连
    if (this.status !== 'close') {
      connect()
    }
  }
  // 主动关闭
  close() {
    this.status = 'close'
    clearInterval(this.time)
    this.ws.close()
  }
}
